package com.zg.common.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.dao.system.SysThird;
import com.zg.common.core.dao.system.SysThirdDao;
import com.zg.common.web.Req;
import com.zg.common.core.exception.E;
import com.zg.common.core.util.TokenUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.Calendar;

/**
 * 请求鉴权器
 * @author Zxb
 */
@Component
@Data
@RequiredArgsConstructor
public class AuthValidator {
    /**
     * 5分钟
     */
    public static final Long OVERTIME_LIMIT = 300000L;

    private final SysThirdDao thirdDao;

    public void hasAccessToken() {
        String accessToken = Req.getHeader("accessToken");
        if (StrUtil.isEmpty(accessToken)) {
            E.NO_SAFE_TOKEN.happen();
        }
        String result = TokenUtil.validateSafeToken(accessToken);
        if (result == null) {
            E.BAD_SAFE_TOKEN.happen();
        }
    }

    public void validateThirdCall() {
        String appKey = Req.getString("appKey");
        String appSecret = Req.getString("appSecret");
        String random = Req.getString("random");
        Long timestamp = Long.valueOf(Req.getString("timestamp"));
        String sign = Req.getString("sign");

        if (StringUtils.isBlank(appKey) || StringUtils.isBlank(appSecret)) {
            E.UN_SAFE_BAD_SECRET.happen();
        }

        if(!thirdDao.exists(new LambdaQueryWrapper<SysThird>()
                .eq(SysThird::getAppKey, appKey)
                .eq(SysThird::getAppSecret, appSecret))){
            E.UN_SAFE_BAD_SECRET.happen();
        }

        long currTimestamp = Calendar.getInstance().getTimeInMillis();
        boolean timestampValidResult = (currTimestamp - timestamp) < OVERTIME_LIMIT;
        if (!timestampValidResult) {
            E.UN_SAFE_TIMEOUT.happen();
        }

        String currSign = SecureUtil.md5(appSecret + random + timestamp);
        boolean signValidResult = currSign.equals(sign);
        if (!signValidResult) {
            E.UN_SAFE_BAD_SIGN.happen();
        }
    }
}
